<template>
  <div class="search-container">
      <form action="/">
          <van-search
              v-model="searchText"
              show-action
              placeholder="请输入搜索关键词"
              background="#f93e2e"
              @search="onSearch"
              @cancel="onCancel"
              @input="shuru"
          />
      </form>

       <!-- 搜索结果 -->
      <searchResult :jieguo="result" v-if="isResultShow" />

      <!-- 搜索历史记录 -->
      <searchHistory
        v-else
        :histories="searchHistories"
        @clear-search-histories="clearHistory"
        @search="onSearch"
      />
  </div>
</template>

<script>
import searchResult from './components/search-result.vue'
import searchHistory from './components/search-history.vue'
import { getSearchResult } from '@/api/search.js'
import { getItem, setItem } from '@/utils/storage.js'

export default {
  name: 'SearchIndex',
  components: {
    searchResult,
    searchHistory
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      result: [],
      searchHistories: getItem('history') || []
    }
  },
  created () {

  },
  mounted () {

  },

  methods: {
    clearHistory() {
      this.searchHistories = []
      setItem('history', this.searchHistories)
    },
    async onSearch() {
      const { data } = await getSearchResult({
        shop_name: this.searchText,
        pageNum: 1,
        pageSize: 10
      })
      console.log(data)
      if (data.meta.status !== 200) return this.$toast('搜索失败')
      this.result = data.data.rows
      console.log(this.result)
      // this.searchHistories.push(val)

      const index = this.searchHistories.indexOf(this.searchText)
      // if (index !== -1) {
      //   this.searchHistories.splice(index, 1)
      // }
      // }
      // console.log(index)
      if (index === -1) {
        this.searchHistories.unshift(this.searchText)
      }

      // 显示搜索结果
      this.isResultShow = true
      setItem('history', this.searchHistories)
    },
    onCancel() {
      this.$router.back()
    },
    shuru() {
      if (!this.searchText) {
        this.result = []
        this.isResultShow = false
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
